from datetime import datetime
from .dao import OperationDAO
from app.utils.logger import logger

class OperationService:
    def __init__(self, db=None):
        self.db = db
        self.operation_dao = OperationDAO(db=self.db)

    def get_operation_list(self, page=1, page_size=10, filters=None):
        """
        获取操作日志列表
        Args:
            page: 页码
            page_size: 每页数量
            filters: 过滤条件
        Returns:
            tuple: (日志列表, 总记录数)
        """
        conditions = {}
        if filters:
            for key, value in filters.items():
                if value:
                    if key in ['username', 'filename']:
                        conditions[f"{key} LIKE"] = value
                    else:
                        conditions[key] = value
        
        items = self.operation_dao.get_operation_list(page, page_size, conditions)
        total = self.operation_dao.get_total_count(conditions)
        return items, total

    def create_log(self, data):
        """创建操作日志"""
        try:
            log_data = {
                'username': data.get('username', ''),
                'operation_type': data.get('operation_type', ''),
                'filename': data.get('filename', ''),
                'status': data.get('status', 0),  # 0-失败，1-成功
                'report_url': data.get('report_url', ''),
                'created_at': datetime.now(),
                'description': data.get('description', '')
            }
            return self.operation_dao.create(log_data)
        except Exception as e:
            logger.error(f"创建操作日志失败: {str(e)}")
            return None